<form class="layui-form seller-form" action="">

    <div class="layui-form-item">

        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">年度：</label>
            <div class="layui-input-inline" id="year_box">
                <select name="year" lay-filter="year" id="year" list="year_list" lay-search>
                    <option value=""></option>
                    <datalist  id="year_list" lay-search>
                        {volist name="yearList" id="yearList"}
                        <option value="{$yearList.id}">{$yearList.year}</option>
                        {/volist}
                    </datalist>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">季度：</label>
            <div class="layui-input-inline" id="season_box">
                <select name="season" lay-filter="season" id="season" list="season_list" lay-search>
                    <option value=""></option>
                    <datalist  id="season_list" lay-search>
                        {volist name="seasonList" id="seasonList"}
                        <option value="{$seasonList.season_id}">{$seasonList.season_name}</option>
                        {/volist}
                    </datalist>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">部/院：</label>
            <div class="layui-input-inline">
                <select name="dep_id" lay-filter="dep_id" id="dep_id" list="dep_list" lay-search>
                    <option value=""></option>
                    <datalist  id="dep_list" lay-search>
                        {volist name="deptList" id="deptList"}
                        <option value="{$deptList.bmdm}">{$deptList.bmmc}</option>
                        {/volist}
                    </datalist>
                </select>
            </div>	
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">专业：</label>
            <div class="layui-input-inline" id="specialty_box">
                <select name="specialty_id" lay-filter="specialty_id" id="specialty_id" list="specialty_list" lay-search>
                    <option value=""></option>
                    <datalist  id="specialty_list" lay-search>
                        {volist name="specialtyList" id="specialtyList"}
                        <option value="{$specialtyList.zydm}">{$specialtyList.zymc}</option>
                        {/volist}
                    </datalist>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">班级：</label>
            <div class="layui-input-inline" id="class_box">
                <select name="class_id" lay-filter="class_id" id="class_id" list="class_list" lay-search>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">方向：</label>
            <div class="layui-input-inline" id="dir_box">
                <select name="dir" lay-filter="dir" id="dir" list="dir_list" lay-search>
                    <option value=""></option>
                    <datalist  id="dir_list" lay-search>
                        {volist name="dirList" id="dirList"}
                        <option value="{$dirList.id}">{$dirList.name}</option>
                        {/volist}
                    </datalist>
                </select>
            </div>
        </div>
        
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">教材：</label>
            <div class="layui-input-inline" id="xh_box">
                <input type="text" id="book_name" name="book_name" class="layui-input" value="" placeholder="请输入教材关键字" ></input>
            </div>
        </div> 
        <div class="layui-inline">
            <button class="layui-btn layui-btn-sm" lay-submit lay-filter="search"><i 
                    class="iconfont icon-chaxun"></i>查询</button>
            <button id="exportBtn" class="layui-btn layui-btn-sm layui-btn-disabled" lay-submit lay-filter="export-bookplan"><i
                    class="iconfont icon-clouddownload" style="font-size: 20px !important;" disabled></i>导出</button> 
            <button type="button" class="layui-btn layui-btn-sm" lay-submit lay-filter="import-bookplan"><i
                    class="iconfont icon-cloudupload" style="font-size: 20px !important;" disabled></i>教材计划导入</button>
            <!-- <button type="button" class="layui-btn layui-btn-sm" lay-submit lay-filter="import-bookprice"><i
                    class="iconfont icon-cloudupload" style="font-size: 20px !important;" disabled></i>教材定价导入</button> -->
         </div>
    </div>

</form>

<div class="table-body">
    <table id="bookPlanTable" lay-filter="bookPlanTable"></table>
</div>

<div id="exportBookPlan" style="display: none;">
    <form class="layui-form export-form" action="">
        <div class="layui-form-item">
            <div class="layui-margin-10">
                <blockquote class="layui-elem-quote layui-text">
                    请先筛选要导出的教材计划，默认导出全部
                </blockquote>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label">任务名称：</label>
                <input type="text" name="taskname" lay-verify="title" style="width:200px;" placeholder="请输入任务名称"
                    autocomplete="off" class="layui-input">
            </div>
        </div>
    </form>
</div>

<div id="importBookPlan" style="display: none;">
    <form class="layui-form import-form" method="post" action="{:url('ietask/import')}" enctype="multipart/form-data">
        <div class="layui-form-item">
            <div class="layui-margin-10">
                <blockquote class="layui-elem-quote layui-text">
                    请先下载<a href="{:url('ietask/importTemplete',['tplName'=>'bookplan'])}">导入模板(不支持迅雷等下载工具)</a>
                </blockquote>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">
                    <input type="file" class="layui-file" name="importFile" id="importFile">
                    <input type="hidden" name="model" value="bookPlan">
                </label>
            </div>
        </div>
    </form>
</div>

<div id="importBookPrice" style="display: none;">
    <form class="layui-form import-form" method="post" action="{:url('ietask/import')}" enctype="multipart/form-data">
        <div class="layui-form-item">
            <div class="layui-margin-10">
                <blockquote class="layui-elem-quote layui-text">
                    请先下载<a href="{:url('ietask/importTemplete',['tplName'=>'bookprice'])}">导入模板(不支持迅雷等下载工具)</a>
                </blockquote>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">
                    <input type="file" class="layui-file" name="importFile" id="importFile">
                    <input type="hidden" name="model" value="BookPrice">
                </label>
            </div>
        </div>
    </form>
</div>

<script>
    layui.use(['table', 'form', 'layer', 'laydate'], function () {
        var layer = layui.layer, table = layui.table, form = layui.form, date = layui.laydate;
        // 定义变量保存当前页面和当前页面数据条数
        var currPage; 
        var dataNum;

        //执行渲染
        var mainTable = table.render({
            id: 'bookPlanTable',
            elem: '#bookPlanTable', //指定原始表格元素选择器（推荐id选择器）
            height: 'full-165',
            cellMinWidth: '80',
            page: 'true',
            limit: '20',
            url: "{:url('BookCommon/returnNull')}",
            toolbar: '#toolbarDemo',
            defaultToolbar: [],
            //url: "{:url('BookDraw/bookPlanindex')}",
            cols: [[ //标题栏
                { type: 'checkbox' },
                { field: 'id', title: 'ID', hide:true},
                { field: 'plan_year', sort: true, title: '年度', width: 80, align: 'center' },
                { field: 'plan_season', sort: true, title: '季度', width: 80, align: 'center' },
                { field: 'dept_name', sort: true, title: '部/院', width: 120, align: 'center' },
                { field: 'specialty_name', sort: true, title: '专业', width: 200, align: 'center' },
                { field: 'plan_class_name', sort: true, title: '班级', width: 240, align: 'center' },
                { field: 'plan_dir', sort: true, title: '方向', width: 80, align: 'center' },
                { field: 'course_name', sort: true, title: '课程名称', width: 200, align: 'center' },
                { field: 'book_name', sort: true, title: '教材名称', width: 200, align: 'center' },
                { field: 'book_author', sort: true, title: '主编', width: 120, align: 'center' },
                { field: 'book_concern', sort: true, title: '出版社', width: 160, align: 'center' },
                { field: 'book_isbn', sort: true, title: 'ISBN', width: 160, align: 'center' },
                { field: 'plan_price', sort: true, title: '单价', width: 80, align: 'right' },
                { field: 'book_disc', sort: true, title: '折扣', width: 80, align: 'center' },
                { field: 'plan_student', sort: true, title: '数量', width: 80, align: 'center' },
                { field: 'plan_book_num', sort: true, title: '教材数量', width: 120, align: 'center' },
                { field: 'username', title: '操作员', width: 120, align: 'center' },
                { field: 'plan_date', title: '更新时间', width: 160, align: 'center' },
                { width: 120, title: '操作', align: 'center', toolbar: '#hooksBar' }
            ]], //设置表头
            done: function(res, curr, count){
                // 判断加载结果数量是否大于0
                if(count>0){
                    $("#exportBtn").removeClass("layui-btn-disabled");
                    $('#exportBtn').removeAttr("disabled");
                } else {
                    $('#exportBtn').addClass("layui-btn-disabled");
                    $('#exportBtn').attr("disabled", true);
                }

                // 给变量赋值 
                dataNum = res.data.length;
                currPage = curr;
            }
            // where: {"year":$("#year").val(), "season": $("#season").val(), "dir": $("#dir").val(), "is_ff": $("#is_ff").val()} 
            //,…… //更多参数参考右侧目录：基本参数选项
        });
 
        layui.use('form', function () {
            // 联动年度
            form.on('select(year)', function (data) {
                getClass(data);
            });

            // 联动专业  
            form.on('select(specialty_id)', function (data) {
                getClass(data);
            });

            // 联动部门
            form.on('select(dep_id)', function (data) {
                getSpecialty(data);
            });
        });

        // 得到专业
        function getSpecialty(data) {
            $.ajax({
                type: 'get',
                url: "{:url('BookCommon/getSpecicalties')}",
                data: 'bmdm=' + data.value,
                success: function(e) {
                    if(e.status) {
                        $("#specialty_id").empty();//清空下拉框的值
                        $('#specialty_id').append(new Option('', ''));// 下拉菜单里添加元素
                        $("#class_id").empty();//清空下拉框的值
                        $('#class_id').append(new Option('', ''));// 下拉菜单里添加元素
                        $.each(e.data.data, function (index, item) {
                            $('#specialty_id').append(new Option(item.zymc, item.zydm));// 下拉菜单里添加元素
                        });
                        layui.form.render("select");//重新渲染 固定写法
                    } else {
                        layer.msg(e.msg);
                    }
                }
            });
        };
        
        // 得到班级
        function getClass(data) { 
            var dept = $("#dep_id").val();
            var specialty_id = $("#specialty_id").val();
            var year = $("#year").val();
            var season = $("#season").val();

            $.ajax({
                type: 'get',
                url: "{:url('BookCommon/getClasses')}",
                data: {
                        "bmdm": dept,
                        "zydm": specialty_id,
                        "plan_year":  year,
                        "plan_season": season
                    },
                success: function(e) {
                    if(e.status) {
                        $("#class_id").empty();//清空下拉框的值
                        $('#class_id').append(new Option('', ''));// 下拉菜单里添加元素
                        $.each(e.data.data, function (index, item) {
                            $('#class_id').append(new Option(item.plan_class_name, item.plan_class_id));// 下拉菜单里添加元素
                        });
                        layui.form.render("select");//重新渲染 固定写法
                    } else {
                        layer.msg(e.msg);
                    }
                }
            });
        };

        // 查询
        form.on('submit(search)', function (data) {
            table.reload('bookPlanTable', {
                where: data.field,
                page: {curr: 1},
                url: "{:url('BookPlan/index')}",
            });
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        //教材计划导出
        layui.form.on('submit(export-bookplan)', function (data) {
            layer.open({
                type: 1,
                title: '教材计划导出',
                area: ['400px', '248px'], //宽高
                btn: ['确定', '取消'],
                content: $("#exportBookPlan").html(),
                success: function () {
                    $(':focus').blur();
                    this.enterEsc = function(event){
                        if(event.keyCode === 13){
                            if(!$(".layui-layer-btn0").hasClass("layui-btn-disabled")){
                                $(".layui-layer-btn0").addClass("layui-btn-disabled");

                                //判断是否有选中
                                var filter = $(".seller-form").serialize();
                                $(".export-form:last").append("<input type='hidden' name='filter' value='" + filter + "'>");
                                var data = $(".export-form:last").serializeArray();
                                data.push({ 'name': 'model', 'value': 'BookPlan' });

                                if($.trim(data[0]['value']) == '') {
                                    layer.msg('请填写任务名称！', { time: 1300 });
                                    $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                                    return false;
                                }

                                JsPost("{:url('Ietask/export')}", data, function (res) {
                                        layer.msg(res.msg, { time: 1500 }, function () {
                                            if (res.status) {
                                                layer.closeAll();
                                                //执行跳转
                                                var topLayui = parent === self ? layui : top.layui;
                                                topLayui.index.openTabsPage('/manage/ietask/index.html', '导入导出');
                                            } else {
                                                $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                                            }
                                        });
                                    }
                                );
                            }
                            return false; //阻止系统默认回车事件
                        }
                    };
                    $(document).on('keydown', this.enterEsc);	//监听键盘事件，关闭层
                },
                yes: function () {
                    if(!$(".layui-layer-btn0").hasClass("layui-btn-disabled")){
                        $(".layui-layer-btn0").addClass("layui-btn-disabled");

                        //判断是否有选中
                        var filter = $(".seller-form").serialize();
                        $(".export-form:last").append("<input type='hidden' name='filter' value='" + filter + "'>");
                        var data = $(".export-form:last").serializeArray();
                        
                        if($.trim(data[0]['value']) == '') {
                            layer.msg('请填写任务名称！', { time: 1300 });
                            $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                            return false;
                        }

                        data.push({ 'name': 'model', 'value': 'BookPlan' });
                        JsPost("{:url('Ietask/export')}", data, function (res) {
                                layer.msg(res.msg, { time: 1500 }, function () {
                                    if (res.status) {
                                        layer.closeAll();
                                        //执行跳转
                                        var topLayui = parent === self ? layui : top.layui;
                                        topLayui.index.openTabsPage('/manage/ietask/index.html', '导入导出');
                                    } else {
                                        $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                                    }
                                });
                            }
                        );
                    }
                }, btn2: function () {
                    layer.closeAll();
                }, end: function(){
                    $(document).off('keydown', this.enterEsc);	        //解除键盘关闭事件
                }
            });
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        //导入教材计划信息
        layui.form.on('submit(import-bookplan)', function (data) {
            var topLayui = parent === self ? parent.window.layui : top.parent.window.layui;
            topLayui.index.openTabsPage('{:url("BookPlan/importBookPlan")}', '导入教材计划信息'); 
            return false;
        }); 
        
        //导入教材定价信息
        layui.form.on('submit(import-bookprice)', function (data) {
            var topLayui = parent === self ? parent.window.layui : top.parent.window.layui;
            topLayui.index.openTabsPage('{:url("BookPlan/importBookPrice")}', '导入教材定价信息'); 
            return false;
        }); 

        //头工具栏事件
        layui.table.on('toolbar(bookPlanTable)', function (obj) {
            var checkStatus = table.checkStatus('bookPlanTable');
            data = checkStatus.data;
            if(data.length==0){
                layer.msg('请先选择计划！', { time: 1300 });
                return false;
            }

            let ids = ""; 
            $.each(data, function(index, item){ 
                ids += item.id + ",";
            })
            ids = ids.substring(0, ids.length - 1);

            switch (obj.event) {
                case 'planDel': 
                    layer.confirm('您确定删除吗？', {
                        btn: ['确认', '取消'] //按钮
                    }, function () {
                        JsPost("{:url('BookPlan/del')}", {ids:ids}, function (res) {
                            //删除逻辑中判断只有一条数据时应该刷新前一页信息
                            layer.msg(res.msg);
                            if(res.status){
                                if(dataNum == 1){
                                    currPage = currPage - 1;
                                }

                                table.reload('bookPlanTable', {
                                    page: {
                                        curr: currPage
                                    }
                                });
                                return false;
                            }
                        });
                    }, function () {
                        layer.close(1);
                    });
                    break;
                case 'batchEditNum': 
                    JsGet("{:url('BookPlan/batchEditNum')}", function(e){
                        if ((e.hasOwnProperty('status') && !e.status) || (e.hasOwnProperty('code') && e.code == 0)) {
                            layer.msg(e.msg); return false;
                        }

                        window.box = layer.open({
                            type: 1,
                            content: e,
                            area: ['308px', '190px'],
                            title:'批量改数量',
                            btn: ['确定','取消'],
                            yes: function(index, layero){
                                if(!$(".layui-layer-btn0").hasClass("layui-btn-disabled")){
                                    $(".layui-layer-btn0").addClass("layui-btn-disabled");
                                    
                                    var items = $("#batchEditNum_edit_form").serializeArray();
                                    items.push({name: "ids", value: ids});

                                    if(items['0']['value'] <= 0) {
                                        $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                                        layer.msg('请输入合法的数量', { time: 1300 });
                                        return false;
                                    }

                                    if($('#plan_book_num').val() != ''){
                                        //保存支付方式
                                        $.ajax({
                                            type:'post',
                                            url: "{:url('BookPlan/saveBookNum')}",
                                            data: items,
                                            success:function(res){
                                                if(res.status){
                                                    layer.close(index);
                                                    layer.msg(res.msg,{time:1300},function(){
                                                        layui.table.reload('bookPlanTable', {
                                                            where: data.field, 
                                                            page: {curr: 1},
                                                            url: "{:url('BookPlan/index')}",
                                                        });
                                                    });
                                                }else{
                                                    $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                                                    layer.msg(res.msg);
                                                }
                                            }
                                        });
                                    }else{
                                        layer.msg('请输入教材数量');
                                    }
                                }
                            }
                        });
                    });
                    break;
                // case 'batchEditPrice': 
                //     JsGet("{:url('BookPlan/batchEditPrice')}", function(e){
                //         if ((e.hasOwnProperty('status') && !e.status) || (e.hasOwnProperty('code') && e.code == 0)) {
                //             layer.msg(e.msg); return false;
                //         }

                //         window.box = layer.open({
                //             type: 1,
                //             content: e,
                //             area: ['308px', '190px'],
                //             title:'批量改价格',
                //             btn: ['确定','取消'],
                //             yes: function(index, layero){
                //                 if(!$(".layui-layer-btn0").hasClass("layui-btn-disabled")){
                //                     $(".layui-layer-btn0").addClass("layui-btn-disabled");
                                    
                //                     var items = $("#batchEditPrice_edit_form").serializeArray();
                //                     items.push({name: "ids", value: ids});

                //                     if(items['0']['value'] <= 0) {
                //                         $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                //                         layer.msg('请输入合法的价格', { time: 1300 });
                //                         return false;
                //                     }

                //                     if($('#plan_price').val() != ''){
                //                         //保存支付方式
                //                         $.ajax({
                //                             type:'post',
                //                             url: "{:url('BookPlan/saveBookPrice')}",
                //                             data: items,
                //                             success:function(res){
                //                                 if(res.status){
                //                                     layer.close(index);
                //                                     layer.msg(res.msg,{time:1300},function(){
                //                                         layui.table.reload('bookPlanTable', {
                //                                             where: data.field, 
                //                                             page: {curr: 1},
                //                                             url: "{:url('BookPlan/index')}",
                //                                         });
                //                                     });
                //                                 }else{
                //                                     $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                //                                     layer.msg(res.msg);
                //                                 }
                //                             }
                //                         });
                //                     }else{
                //                         layer.msg('请输入单价');
                //                     }
                //                 }
                //             }
                //         });
                //     });
                //     break;
            };
        });

        //监听工具条
        table.on('tool(bookPlanTable)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            
            if(layEvent === 'edit'){ //编辑  
                var url = "{:url('manage/BookPlan/edit')}" + '?id=' + data.id;
                var topLayui = parent === self ? parent.window.layui : top.parent.window.layui;
                topLayui.index.openTabsPage(url, '编辑教材计划'); 
                return false;
            } else if(layEvent === 'copy'){ //编辑 
                var url = "{:url('manage/BookPlan/copy')}" + '?id=' + data.id;
                var topLayui = parent === self ? parent.window.layui : top.parent.window.layui;
                topLayui.index.openTabsPage(url, '复制教材计划'); 
                return false;
            }
        });

    })
  
    $("#year").val({$year});  // 年度：
    $("#season").val({$season});  // 季度：春季
    $("#dir").val(1);  // 默认方向：就业
</script>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm layui-btn-danger" id = "planDel" lay-event="planDel">删除计划</button>
        <button class="layui-btn layui-btn-sm" id = "batchEditNum" lay-event="batchEditNum">批量改数量</button>
        <!-- <button class="layui-btn layui-btn-sm" id = "batchEditPrice" lay-event="batchEditPrice">批量改价格</button> -->
    </div>
</script>

<script type="text/html" id="hooksBar">
    <a class="layui-btn layui-btn-xs" name="edit" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-xs" name="copy" lay-event="copy">复制</a>
</script>